<template>
  <div>
    <!-- 面包屑导航区 ----------------------------------------------------------->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -------------------------------------------------------------->
    <el-card>
      <!-- 搜索与添加按钮区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" @clear="getUserList"
          v-model="queryInfo.query" clearable >
            <el-button slot="append" icon="el-icon-search" @click="getUserList" ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">新增用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 ------------------------------------------------------------------>
      <el-table :data="userlist" border stripe>
        <el-table-column label="序号" type="index" width="50px"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="Email" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" 
                @change="onUserStateChange(scope.row)" ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit"   size="mini" ></el-button>
            <el-button type="danger"  icon="el-icon-delete" size="mini" ></el-button>
            <el-tooltip content="分配角色" placement="top-end" :enterable="false" 
                popper-class="poper-style" transition="none" >
              <el-button type="warning" icon="el-icon-setting" size="mini" 
                  @click="setRole(scope.row)" ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具栏 ---------------------------------------------------->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 ----------------------------------------------------->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 对话框内容主题区 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 电子邮件 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 --------------------------------------------------------->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" 
        vidth="50%" @close="roleDilogClosed">
      <div>
        <p>当前用户：{{curUserInfo.username}}</p>
        <p>当前角色：{{curUserInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="选择角色">
            <el-option v-for="item in roleList" :key="item.id"
                :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible=false">取消</el-button>
        <el-button @click="saveRoleInfo" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入正确的手机号"));
      }
    };

    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (regEmail.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入正确的邮箱"));
      }
    };

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      dialogVisible: false,     // 新增用户对话框是否可见 flag
      roleDialogVisible: false, // 分配角色对话框是否可见 flag
      // 添加数据表单
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            require: true,
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            require: true,
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [{ validator: checkEmail, trigger: "blur" }],
        mobile: [{ validator: checkMobile, trigger: "blur" }],
      },
      // 当前操作用户信息
      curUserInfo: {},
      roleList: [],   // 所有角色列表
      selectedRoleId:'' // 已选中角色id
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    /////////////////////////////////
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //////////////////////////////////
    handleSizeChange(size) {
      this.queryInfo.pagesize = size;
      this.getUserList();
    },
    //////////////////////////////////
    handleCurrentChange(current) {
      this.queryInfo.pagenum = current;
      this.getUserList();
    },
    // 监听 switch 状态改变 ///////////
    async onUserStateChange(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 分配权限对话框 /////////////////
    async setRole(userInfo){
      this.curUserInfo = userInfo;
      // 获取所有角色列表
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200) {
        return this.message.error("获取所有角色列表失败")
      }
      this.roleList = res.data;
      this.roleDialogVisible = true;
    },
    // 保存用户角色
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error("请选择用户角色");
      }
      const {data:res} = await this.$http.put(
                          `users/${this.curUserInfo.id}/role`, 
                          {rid: this.selectedRoleId}
                        );
      if(res.meta.status !== 200){
        return this.$message.error("修改角色失败")
      }
      this.$message.success("修改权限成功");
      this.getUserList();
      this.roleDialogVisible = false;

    },
    // 角色分配对话框关闭事件///////////
    roleDilogClosed(){
      this.curUserInfo = {};
      this.selectedRoleId = '';
    }
  },
};
</script>

<style lang="less" scoped></style>
